/* eslint-disable */
<template>
  <!-- 课程详情页面容器 -->
  <div class="course-detail-container">
    <!-- 课程头部信息 -->
    <div class="course-header">
      <!-- 返回按钮放在最左上角 -->
      <div class="back-wrapper">
        <el-button class="back-button" @click="goToHomepage">返回</el-button>
      </div>
      <div class="header-bg"></div> <!-- 背景层 -->
      <div class="course-info" v-loading="loadingCourse">
        <!-- 移除了返回按钮，只保留课程标题 -->
        <h2>{{ course.name }}</h2>
        <p class="teacher">授课教师：{{ course.teacherName }}</p>
      </div>
      <!-- 删除学生人数、作业数量和学习进度的统计信息区域 -->
    </div>

    <!-- 功能导航 -->
    <div class="nav-section">
      <el-menu :default-active="activeTab" mode="horizontal" @select="handleSelect">
        <el-menu-item index="homework">作业</el-menu-item>
        <el-menu-item index="announcement">公告</el-menu-item>
        <el-menu-item index="quiz">随堂测试</el-menu-item>
      </el-menu>
    </div>

    <!-- 内容区域 -->
    <div class="content-section">
      <!-- 作业内容 -->
      <div v-if="activeTab === 'homework'" class="homework-content">
        <el-table v-loading="loadingAssignments" :data="assignments" style="width: 100%">
          <el-table-column prop="title" label="作业名称"></el-table-column>
          <el-table-column prop="deadline" label="截止时间" width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.deadline) }}
              <div v-if="isBeforeDeadline(scope.row.deadline) && scope.row.status !== 'graded'">
                <el-tag size="mini" type="danger" v-if="isCloseToDeadline(scope.row.deadline)">
                  即将截止
                </el-tag>
              </div>
              <div v-else-if="isOverdue(scope.row.deadline) && scope.row.status !== 'graded'">
                <el-tag size="mini" type="danger">已超期</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status || 'pending')">
                {{ getStatusText(scope.row.status || 'pending') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="成绩" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.status === 'graded'">{{ scope.row.score }}</span>
              <el-tag v-else-if="scope.row.status === 'submitted'" type="info">待批改</el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button 
                size="mini" 
                :type="scope.row.status === 'graded' ? 'info' : 'primary'" 
                @click="handleHomework(scope.row)"
                :title="scope.row.status === 'graded' ? '查看批改结果' : ''"
              >
                {{ scope.row.status === 'graded' ? '查看作业' : (scope.row.status === 'submitted' ? '重新提交' : (scope.row.status === 'overdue' ? '超期提交' : '提交作业')) }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="assignments.length === 0 && !loadingAssignments" description="暂无作业"></el-empty>
      </div>

      <!-- 公告内容 -->
      <div v-if="activeTab === 'announcement'" class="announcement-content">
        <div v-loading="loadingAnnouncements">
          <div v-for="(notice, index) in announcements" :key="index" class="notice-item">
          <div class="notice-header">
            <h4>{{ notice.title }}</h4>
              <span class="notice-time">{{ formatDate(notice.createTime) }}</span>
          </div>
          <p class="notice-content">{{ notice.content }}</p>
          </div>
          <el-empty v-if="announcements.length === 0 && !loadingAnnouncements" description="暂无公告"></el-empty>
        </div>
      </div>
      
      <!-- 随堂测试内容 -->
      <div v-if="activeTab === 'quiz'" class="quiz-content">
        <div v-loading="loadingQuizzes">
          <el-table :data="quizzes" style="width: 100%">
            <el-table-column prop="title" label="测试标题"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getQuizStatusType(scope.row.status)">{{ getQuizStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button 
                  size="mini" 
                  :type="scope.row.status === 1 ? 'primary' : 'info'" 
                  @click="handleQuiz(scope.row)"
                  :disabled="Number(scope.row.status) === 0">
                  {{ Number(scope.row.status) === 0 ? '未开始' : (Number(scope.row.status) === 1 ? '开始答题' : '查看详情') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="quizzes.length === 0 && !loadingQuizzes" description="暂无随堂测试"></el-empty>
        </div>
      </div>
    </div>

    <!-- 作业提交对话框 -->
    <el-dialog 
      :title="isViewOnly ? '作业详情' : (currentHomework.status === 'submitted' ? '重新提交作业' : (currentHomework.originalStatus === 'overdue' ? '超期提交作业' : '提交作业'))" 
      :visible.sync="homeworkDialogVisible" 
      width="60%"
      :close-on-click-modal="false">
      <el-form :model="homeworkForm" :rules="homeworkRules" ref="homeworkForm" label-width="80px">
        <el-form-item label="作业标题" class="form-title">
          <span>{{ currentHomework.title }}</span>
        </el-form-item>
        <el-form-item label="截止时间">
          <span>{{ formatDate(currentHomework.deadline) }}</span>
          <el-tag 
            size="mini" 
            type="danger" 
            v-if="isCloseToDeadline(currentHomework.deadline) && isBeforeDeadline(currentHomework.deadline)">
            即将截止
          </el-tag>
          <el-tag 
            size="mini" 
            type="danger" 
            v-if="isOverdue(currentHomework.deadline)">
            已超期
          </el-tag>
        </el-form-item>
        <el-form-item label="作业要求">
          <div class="homework-description">{{ currentHomework.description || '暂无作业要求' }}</div>
        </el-form-item>
        <el-form-item label="附件" v-if="currentHomework.attachmentUrl">
          <div class="attachment-list">
            <div class="attachment-item">
              <i class="el-icon-document"></i>
              <span>{{ getOriginalFileName(currentHomework.attachmentUrl) || '作业附件' }}</span>
              <el-button type="text" @click="downloadAttachment(currentHomework.attachmentUrl)">下载</el-button>
            </div>
          </div>
        </el-form-item>
        
        <!-- 添加文件上传组件 - 仅在非只读模式显示 -->
        <el-form-item label="上传作业" prop="file" v-if="!isViewOnly">
          <el-upload
            class="upload-with-file"
            action="#"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            :limit="1">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">支持任意格式文件，单个文件不超过10MB</div>
          </el-upload>
        </el-form-item>
        
        <!-- 合并后的提交历史记录表格 -->
        <div class="submission-history-section" v-if="submissionHistory && submissionHistory.length > 0">
          <h5>提交历史记录</h5>
          <el-table :data="submissionHistory" size="mini" style="width: 100%">
            <el-table-column prop="version" label="版本" width="80"></el-table-column>
            <el-table-column prop="submitTime" label="提交时间" width="180"></el-table-column>
            <el-table-column label="文件" min-width="120">
              <template slot-scope="scope">
                <a 
                  class="file-link" 
                  :href="scope.row.fileUrl" 
                  download
                  @click.prevent="directDownload(scope.row.fileUrl)">
                  {{ getOriginalFileName(scope.row.fileUrl) || '提交文件' }}
                </a>
                <el-tag v-if="scope.$index === 0" type="success" size="mini" style="margin-left: 8px;">最新</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : (scope.row.isLatest ? 'primary' : 'info')" size="mini">
                  {{ scope.row.status === 1 ? '已批改' : (scope.$index === 0 ? '当前版本' : '历史版本') }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
            </div>
        <!-- 教师批改信息（如果已批改） -->
        <div v-if="currentHomework.status === 'graded'" class="grade-section">
          <h5>批改结果</h5>
          <div class="grade-info">
            <div class="grade-score">得分: <span class="score">{{ currentHomework.score || '未评分' }}</span></div>
            <div class="grade-feedback">
              教师评语: {{ getFeedbackText() }}
            </div>
          </div>
        </div>
        <div class="divider"></div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="isViewOnly" @click="homeworkDialogVisible = false">关 闭</el-button>
        <template v-else>
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary" @click="submitHomework" :loading="submitting">确 定 提 交</el-button>
        </template>
      </span>
    </el-dialog>

    <!-- 作业详情对话框 -->
    <el-dialog 
      title="作业详情" 
      :visible.sync="viewDialogVisible" 
      width="60%"
      :close-on-click-modal="false">
      <div class="homework-detail" v-loading="loadingDetail">
        <div class="detail-header">
          <h3>{{ currentHomework.title }}</h3>
          <p class="detail-deadline">截止时间：{{ formatDate(currentHomework.deadline) }}</p>
        </div>
        
        <div class="divider"></div>
        
        <!-- 作业描述部分 -->
        <div class="description-section">
          <h4>作业要求</h4>
          <div class="homework-description">
            {{ currentHomework.description || '老师未提供作业要求说明' }}
          </div>
      </div>
        
        <div class="divider"></div>
        
        <!-- 教师上传的作业文件 -->
        <div class="attachment-section">
          <h4>作业文件</h4>
          <div v-if="hasAttachment" class="attachment-item">
            <i class="el-icon-document"></i>
            <a 
              class="file-link" 
              :href="attachmentUrl" 
              target="_blank" 
              download
              @click.prevent="directDownload(attachmentUrl)">
              {{ getOriginalFileName(attachmentUrl) || '作业文件' }}
            </a>
          </div>
          <div v-else class="empty-attachment">
            <i class="el-icon-warning-outline"></i>
            <span>老师暂未上传作业文件</span>
          </div>
        </div>
        
        <!-- 学生提交的作业文件（如果已提交） -->
        <div v-if="currentHomework.status === 'submitted' || currentHomework.status === 'graded'" class="submission-section">
          <div class="divider"></div>
          <h4>我的提交</h4>
          <div v-if="submissionUrl || (submissionHistory && submissionHistory.length > 0)" class="attachment-item">
            <i class="el-icon-upload2"></i>
            <a 
              class="file-link" 
              :href="getLatestSubmissionUrl()" 
              download
              @click.prevent="directDownload(getLatestSubmissionUrl())">
              {{ getOriginalFileName(getLatestSubmissionUrl()) || '我的提交' }}
            </a>
            <div class="attachment-info">
              <div class="attachment-time">
                <small>提交时间: {{ formatDate(getLatestSubmissionTime()) }}</small>
              </div>
            </div>
          </div>
          <div v-else class="empty-attachment">
            <i class="el-icon-warning-outline"></i>
            <span>未找到提交文件</span>
          </div>
          
          <!-- 提交历史记录 -->
          <div class="submission-history-section" v-if="submissionHistory && submissionHistory.length > 0">
            <h5>提交历史记录</h5>
            <el-table :data="submissionHistory" size="mini" style="width: 100%">
              <el-table-column prop="version" label="版本" width="80"></el-table-column>
              <el-table-column prop="submitTime" label="提交时间" width="180"></el-table-column>
              <el-table-column label="文件" min-width="120">
                <template slot-scope="scope">
                  <a 
                    class="file-link" 
                    :href="scope.row.fileUrl" 
                    download
                    @click.prevent="directDownload(scope.row.fileUrl)">
                    {{ getOriginalFileName(scope.row.fileUrl) || '提交文件' }}
                  </a>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status === 1 ? 'success' : (scope.row.isLatest ? 'primary' : 'info')" size="mini">
                    {{ scope.row.status === 1 ? '已批改' : (scope.row.isLatest ? '当前版本' : '历史版本') }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 教师批改信息（如果已批改） -->
          <div v-if="currentHomework.status === 'graded'" class="grade-section">
            <h5>批改结果</h5>
            <div class="grade-info">
              <div class="grade-score">得分: <span class="score">{{ currentHomework.score || '未评分' }}</span></div>
              <div class="grade-feedback">
                教师评语: {{ getFeedbackText() }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    
    <!-- 随堂测试答题对话框 -->
    <el-dialog 
      :title="currentQuiz ? currentQuiz.title : '随堂测试'" 
      :visible.sync="quizDialogVisible" 
      :close-on-click-modal="false"
      width="60%">
      <div v-loading="quizLoading">
        <div class="quiz-info">
          <div class="quiz-description" v-if="currentQuiz && currentQuiz.description">
            {{ currentQuiz.description }}
          </div>
          
          <!-- 题目列表 -->
          <div class="quiz-questions">
            <div 
              v-for="(question, index) in quizQuestions" 
              :key="question.questionId" 
              class="quiz-question">
              <div class="question-title">
                <span class="question-number">{{ index + 1 }}.</span>
                {{ question.questionText }}
              </div>
              
              <!-- 选项 -->
              <div class="question-options">
                <div 
                  v-for="(option, optIndex) in JSON.parse(question.options || '[]')" 
                  :key="optIndex"
                  class="option-item"
                  :class="{ 'option-selected': quizForm.answers[index] && quizForm.answers[index].answer === String(optIndex) }"
                  @click="selectAnswer(index, optIndex)">
                  <div class="option-marker">{{ ['A', 'B', 'C', 'D'][optIndex] }}</div>
                  <div class="option-text">{{ option }}</div>
                </div>
              </div>
            </div>
            
            <div v-if="quizQuestions.length === 0" class="no-questions">
              <el-empty description="暂无题目"></el-empty>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="quizDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitQuizAnswers" :loading="quizSubmitting">提交答案</el-button>
      </span>
    </el-dialog>
    
    <!-- 测试结果对话框 -->
    <el-dialog 
      :title="currentQuiz ? (currentQuiz.title + ' - 测试结果') : '测试结果'" 
      :visible.sync="resultDialogVisible" 
      :close-on-click-modal="false"
      width="60%">
      <div v-loading="quizLoading">
        <!-- 如果已提交过 -->
        <div v-if="quizSubmission" class="quiz-result">
          <!-- 分数展示 -->
          <div class="quiz-score">
            <div class="score-value">{{ quizSubmission.score || 0 }}</div>
            <div class="score-text">分数</div>
          </div>
          
          <!-- 正确率 -->
          <div class="quiz-stats">
            <div class="stats-item">
              <div class="stats-value">{{ quizSubmission.correctCount || 0 }}/{{ quizQuestions.length }}</div>
              <div class="stats-text">正确题数</div>
            </div>
            <div class="stats-item">
              <div class="stats-value">{{ Math.round(((quizSubmission.correctCount || 0) / quizQuestions.length) * 100) }}%</div>
              <div class="stats-text">正确率</div>
            </div>
          </div>
          
          <!-- 题目列表（带答案） -->
          <div class="quiz-questions result-questions">
            <div 
              v-for="(question, index) in quizQuestions" 
              :key="question.questionId" 
              class="quiz-question">
              <div class="question-title">
                <span class="question-number">{{ index + 1 }}.</span>
                {{ question.questionText }}
              </div>
              
              <!-- 选项（带正确/错误标记） -->
              <div class="question-options">
                <div 
                  v-for="(option, optIndex) in JSON.parse(question.options || '[]')" 
                  :key="optIndex"
                  class="option-item"
                  :class="getOptionClass(question, optIndex)">
                  <div class="option-marker">{{ ['A', 'B', 'C', 'D'][optIndex] }}</div>
                  <div class="option-text">{{ option }}</div>
                </div>
              </div>
              
              <!-- 答案解释 -->
              <div class="question-explanation" v-if="String(question.correctAnswer) !== ''">
                <div class="explanation-text">
                  正确答案：{{ ['A', 'B', 'C', 'D'][Number(question.correctAnswer)] }}
                </div>
                <div class="explanation-text user-answer" v-if="getUserAnswer(question)">
                  您的选择：{{ ['A', 'B', 'C', 'D'][Number(getUserAnswer(question))] }}
                  <span v-if="getUserAnswer(question) === question.correctAnswer" class="answer-correct">
                    <i class="el-icon-check"></i> 正确
                  </span>
                  <span v-else class="answer-wrong">
                    <i class="el-icon-close"></i> 错误
                  </span>
                </div>
              </div>
            </div>
            
            <div v-if="quizQuestions.length === 0" class="no-questions">
              <el-empty description="暂无题目"></el-empty>
            </div>
          </div>
        </div>
        
        <!-- 如果未提交 -->
        <div v-else class="no-submission">
          <el-empty description="您还没有提交过此测试，无法查看结果"></el-empty>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resultDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCourseDetail, getCourseAnnouncements, getCourseAssignments, getStudentAssignmentDetail, submitAssignment, getAssignmentById, createAssignmentAllocation } from '@/api/student'
import { mapGetters } from 'vuex'
import { getSubmissionByAssignmentIdAndStudentId, getSubmissionsByAssignmentId } from '@/api/submission'
import { getStudentQuizList, getQuizQuestions, submitQuiz, getStudentSubmission, isSubmitted } from '@/api/quiz'

export default {
  name: 'CourseDetail',
  data() {
    return {
      activeTab: 'homework', // 默认选中作业标签页
      courseId: '',
      classId: '',
      course: {
        name: '',
        teacherName: '',
        studentCount: 0,
        progress: 0
      },
      assignments: [],
      announcements: [],
      loadingCourse: false,
      loadingAssignments: false,
      loadingAnnouncements: false,
      homeworkDialogVisible: false,
      currentHomework: {},
      homeworkForm: {
        file: null
      },
      fileList: [],
      homeworkRules: {
        file: [
          { required: true, message: '请上传作业文件', trigger: 'change' }
        ]
      },
      submitting: false,
      uploadProgress: 0,
      showUploadProgress: false,
      allocationId: null,
      loadingDetail: false,
      isViewOnly: false, // 标记是否处于只读模式（查看已批改作业）
      submissionHistory: [], // 提交历史记录
      loadingHistory: false, // 加载历史记录状态
      loadingQuizzes: false, // 加载随堂测试状态
      quizzes: [], // 随堂测试列表
      quizDialogVisible: false, // 答题对话框可见性
      resultDialogVisible: false, // 结果对话框可见性
      currentQuiz: null, // 当前测试
      quizQuestions: [], // 测试题目
      quizForm: { // 答题表单
        answers: []
      },
      quizLoading: false, // 加载测试状态
      quizSubmitting: false, // 提交测试状态
      quizSubmission: null // 测试提交结果
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    studentId() {
      return this.userInfo.studentId || localStorage.getItem('studentId')
    },
    
    // 判断是否有附件
    hasAttachment() {
      return Boolean(this.attachmentUrl)
    },
    
    // 获取附件URL（尝试多个可能的字段）
    attachmentUrl() {
      if (!this.currentHomework) return ''
      
      // 直接获取到的attachmentUrl字段（来自合并的数据）
      if (this.currentHomework.attachmentUrl) {
        return this.currentHomework.attachmentUrl
      }
      
      // 如果存在assignment对象，优先从中获取resourceUrl
      if (this.currentHomework.assignment && this.currentHomework.assignment.resourceUrl) {
        return this.currentHomework.assignment.resourceUrl
      }
      
      // 尝试其他可能的字段
      return this.currentHomework.attachment || 
             this.currentHomework.fileUrl || 
             this.currentHomework.assignmentFile || 
             this.currentHomework.resourceUrl ||
             ''
    },
    
    // 学生提交的文件URL
    submissionUrl() {
      if (!this.currentHomework) return ''
      
      // 直接从提交记录获取到的提交文件URL（来自合并的数据）
      if (this.currentHomework.submissionUrl) {
        console.log('使用submissionUrl字段:', this.currentHomework.submissionUrl)
        return this.currentHomework.submissionUrl
      }
      
      // 如果存在submission对象，优先从中获取fileUrl
      if (this.currentHomework.submission && this.currentHomework.submission.fileUrl) {
        console.log('使用submission.fileUrl字段:', this.currentHomework.submission.fileUrl)
        return this.currentHomework.submission.fileUrl
      }
      
      // 尝试其他可能的字段
      const result = this.currentHomework.submissionFile || 
             this.currentHomework.studentAttachment || 
             this.currentHomework.studentFileUrl ||
             ''
             
      console.log('尝试获取提交文件URL:', result)
      return result
    }
  },
  created() {
    // 从路由参数获取课程ID和班级ID
    this.courseId = this.$route.params.id
    this.classId = this.$route.query.classId
    
    // 如果没有提供课程ID或班级ID，显示错误信息
    if (!this.courseId || !this.classId) {
      this.$message.error('缺少课程ID或班级ID参数')
      return
    }
    
    // 获取数据
    this.fetchCourseDetail()
    this.fetchAssignments()
    this.fetchAnnouncements()
    // 删除获取资源方法调用
  },
  methods: {
    // 获取教师评语文本
    getFeedbackText() {
      if (!this.currentHomework) return '无'
      
      // 尝试从多个可能的字段获取评语
      return this.currentHomework.feedback || 
             this.currentHomework.comments || 
             this.currentHomework.comment || 
             this.currentHomework.teacherFeedback || 
             '无'
    },
    
    // 获取最新提交文件的URL
    getLatestSubmissionUrl() {
      // 优先使用当前作业中的提交URL
      if (this.submissionUrl) {
        return this.submissionUrl;
      }
      
      // 如果没有，但有提交历史记录，使用最新记录中的URL
      if (this.submissionHistory && this.submissionHistory.length > 0) {
        // 提交历史已经按时间降序排序，第一个就是最新的
        return this.submissionHistory[0].fileUrl;
      }
      
      return '';
    },
    
    // 获取最新提交时间
    getLatestSubmissionTime() {
      // 优先使用当前作业中的提交时间
      if (this.currentHomework && this.currentHomework.submissionTime) {
        return this.currentHomework.submissionTime;
      }
      
      // 如果没有，但有提交历史记录，使用最新记录中的时间
      if (this.submissionHistory && this.submissionHistory.length > 0) {
        // 这里需要将格式化后的时间字符串转回为日期对象
        try {
          // 尝试解析提交历史中的时间格式，可能是"2025/4/22 16:22:03"这样的格式
          const timeStr = this.submissionHistory[0].submitTime;
          if (timeStr) {
            // 使用原始时间数据，如果提供了
            if (this.submissionHistory[0].rawSubmitTime) {
              return this.submissionHistory[0].rawSubmitTime;
            }
            
            // 尝试将格式化的时间转回日期对象
            return timeStr;
          }
        } catch (e) {
          console.error('解析提交时间出错:', e);
        }
      }
      
      return new Date().toISOString();
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return date.toLocaleString()
    },
    
    // 获取文件名
    getFileName(url) {
      if (!url) return ''
      return url.substring(url.lastIndexOf('/') + 1)
    },
    
    // 判断是否在截止日期之前
    isBeforeDeadline(deadline) {
      if (!deadline) return true
      const now = new Date()
      const deadlineDate = new Date(deadline)
      return now < deadlineDate
    },
    
    // 判断是否已超期
    isOverdue(deadline) {
      if (!deadline) return false
      const now = new Date()
      const deadlineDate = new Date(deadline)
      return now > deadlineDate
    },
    
    // 选择标签页
    handleSelect(key) {
      this.activeTab = key
      this.loadTabData(key)
    },
    
    // 加载标签页数据
    loadTabData(tabKey) {
      switch(tabKey) {
        case 'homework':
          this.fetchAssignments()
          break
        case 'announcement':
          this.fetchAnnouncements()
          break
        case 'quiz':
          this.fetchQuizzes()
          break
      }
    },
    
    // 获取课程详情
    fetchCourseDetail() {
      if (!this.courseId || !this.classId) {
        this.$message.error('课程参数不完整')
        return
      }
      
      this.loadingCourse = true
      getCourseDetail(this.courseId, this.classId, this.studentId)
        .then(res => {
          if (res.code === 200) {
            // 处理后端返回的课程数据
            const data = res.data || {}
            const courseInfo = data.courseInfo || {}
            const classInfo = data.classInfo || {}
            
            this.course = {
              name: courseInfo.courseName || '未知课程',
              teacherName: classInfo.teacherName || '未知教师',
              studentCount: classInfo.studentCount || 0,
              progress: 0, // 暂时设为0
              status: classInfo.status || '未开始'
            }
          } else {
            this.$message.error(res.message || '获取课程详情失败')
          }
        })
        .catch(err => {
          console.error('获取课程详情出错:', err)
          this.$message.error('获取课程详情失败，请稍后重试')
        })
        .finally(() => {
          this.loadingCourse = false
        })
    },
    
    // 获取作业列表
    fetchAssignments() {
      this.loadingAssignments = true
      getCourseAssignments(this.courseId, this.classId, this.studentId)
        .then(res => {
          if (res.code === 200) {
            console.log('获取作业列表成功，原始数据:', JSON.stringify(res.data, null, 2))
            
            // 处理返回的作业数据，确保所有必要字段存在
            const processedAssignments = (res.data || []).map(item => {
              // 创建一个新对象，防止修改原始数据
              const assignment = { ...item };
              
              // 确保id字段存在，如果不存在尝试从assignmentId获取
              if (!assignment.id && assignment.assignmentId) {
                assignment.id = assignment.assignmentId;
              }
              
              // 确保deadline字段格式正确
              if (assignment.deadline && typeof assignment.deadline === 'string') {
                // 尝试将日期字符串转换为标准格式
                try {
                  const date = new Date(assignment.deadline);
                  if (!isNaN(date.getTime())) {
                    assignment.deadline = date.toISOString();
                  }
                } catch (e) {
                  console.warn('日期格式转换失败:', e);
                }
              }
              
              // 记录原始状态用于调试
              console.log(`处理作业 [${assignment.title}] 的状态, 原始状态=${assignment.status}, 类型=${typeof assignment.status}`);
              
              // === 关键修改：强制转换和规范化状态 ===
              
              // 1. 如果状态是数字，转换为字符串
              let statusValue = assignment.status;
              if (typeof statusValue === 'number') {
                const statusMap = {
                  0: 'pending',
                  1: 'submitted',
                  2: 'graded',
                  3: 'overdue'
                };
                const oldStatus = statusValue;
                statusValue = statusMap[statusValue] || 'pending';
                console.log(`数字状态转换: ${oldStatus} -> ${statusValue}`);
              } else if (typeof statusValue === 'string') {
                // 如果是字符串但是数字形式（如"1"），也转换
                if (/^[0-3]$/.test(statusValue)) {
                  const numStatus = parseInt(statusValue, 10);
                  const statusMap = {
                    0: 'pending',
                    1: 'submitted',
                    2: 'graded',
                    3: 'overdue'
                  };
                  const oldStatus = statusValue;
                  statusValue = statusMap[numStatus] || 'pending';
                  console.log(`字符串数字状态转换: ${oldStatus} -> ${statusValue}`);
                }
              }
              
              // 2. 确保状态是有效的文本值
              if (!['pending', 'submitted', 'graded', 'overdue'].includes(statusValue)) {
                console.log(`无效状态 ${statusValue}，设置为默认状态 pending`);
                statusValue = 'pending';
              }
              
              // 3. 更新状态值
              assignment.status = statusValue;
              console.log(`作业 [${assignment.title}] 的最终状态: ${assignment.status}`);
              
              // 4. 检查是否超期未提交
              if (assignment.status === 'pending' && assignment.deadline) {
                const now = new Date();
                const deadlineDate = new Date(assignment.deadline);
                if (now > deadlineDate) {
                  console.log(`作业 [${assignment.title}] 已超期未提交，更新状态为overdue`);
                  assignment.status = 'overdue';
                }
              }
              
              return assignment;
            });
            
            this.assignments = processedAssignments;
            
            // 检查作业数据格式
            if (this.assignments.length > 0) {
              console.log('处理后的第一个作业项:', JSON.stringify(this.assignments[0], null, 2));
              console.log('所有作业状态:', this.assignments.map(a => ({id: a.id, title: a.title, status: a.status})));
              
              // 如果没有id字段，可能需要映射或转换
              if (this.assignments.some(assignment => !assignment.id)) {
                console.warn('有作业项缺少id字段，可能导致查看详情出错');
              }
            }
          } else {
            this.$message.error(res.message || '获取作业列表失败')
          }
        })
        .catch(err => {
          console.error('获取作业列表出错:', err)
          this.$message.error('获取作业列表失败，请稍后重试')
        })
        .finally(() => {
          this.loadingAssignments = false
        })
    },
    
    // 获取公告列表
    fetchAnnouncements() {
      this.loadingAnnouncements = true
      getCourseAnnouncements(this.courseId, this.classId)
        .then(response => {
          if (response.code === 200) {
            this.announcements = response.data || []
            console.log('获取公告列表成功:', this.announcements)
          } else {
            console.error('获取公告列表失败:', response.message)
            this.$message.error(response.message || '获取公告列表失败')
          }
        })
        .catch(error => {
          console.error('获取公告列表出错:', error)
          this.$message.error('获取公告列表失败，请稍后重试')
        })
        .finally(() => {
          this.loadingAnnouncements = false
        })
    },
    
    // 获取随堂测试列表
    fetchQuizzes() {
      this.loadingQuizzes = true
      getStudentQuizList(this.courseId, this.classId, this.studentId)
        .then(response => {
          if (response.code === 200) {
            this.quizzes = response.data || []
            console.log('获取随堂测试列表成功:', this.quizzes)
          } else {
            console.error('获取随堂测试列表失败:', response.message)
            this.$message.error(response.message || '获取随堂测试列表失败')
          }
        })
        .catch(error => {
          console.error('获取随堂测试列表出错:', error)
          this.$message.error('获取随堂测试列表失败，请稍后重试')
        })
        .finally(() => {
          this.loadingQuizzes = false
        })
    },
    
    // 处理作业提交
    handleHomework(homework) {
      // 检查是否有有效的ID
      if (!homework.id) {
        this.$message.warning('作业ID不存在，无法操作')
        console.warn('尝试操作没有ID的作业:', homework)
        return
      }
      
      // 检查作业是否已批改或已提交
      const isGraded = homework.status === 'graded'
      const isSubmitted = homework.status === 'submitted'
      const isOverdue = homework.status === 'overdue'
      
      // 设置是否处于只读模式
      this.isViewOnly = isGraded
      
      if (isGraded) {
        console.log('已批改作业，仅查看详情，ID:', homework.id)
      } else if (isSubmitted) {
        console.log('已提交作业，可重新提交，ID:', homework.id)
      } else if (isOverdue) {
        console.log('超期未提交作业，尝试提交，ID:', homework.id)
        // 将超期作业临时视为未提交状态处理，以解决后端无法找到分配记录的问题
        homework = { ...homework, status: 'pending', originalStatus: 'overdue' }
        console.log('临时修改超期作业状态为pending以正确获取分配记录')
            } else {
        console.log('未提交作业，可以提交，ID:', homework.id)
      }
      
      this.currentHomework = homework
      console.log('准备提交作业, ID:', homework.id, '学生ID:', this.studentId)
      
      // 获取作业详情（包括分配ID）和作业实体
      this.loadingDetail = true
      
      // 对应的API位置
      const apis = [
        getStudentAssignmentDetail(homework.id, this.studentId),
        getAssignmentById(homework.id)
      ]
      
      // 如果是已批改或已提交的作业，添加获取提交记录的API调用
      if (isGraded || isSubmitted) {
        apis.push(getSubmissionByAssignmentIdAndStudentId(homework.id, this.studentId));
      }
      
      Promise.all(apis)
        .then((responses) => {
          const allocationRes = responses[0];
          const assignmentRes = responses[1];
          // 如果有提交记录响应，获取它
          const submissionRes = (isGraded || isSubmitted) ? responses[2] : null;
          
          if (allocationRes.code === 200 && assignmentRes.code === 200) {
            console.log('获取作业分配成功:', allocationRes.data)
            console.log('获取作业详情成功:', assignmentRes.data)
            
            // 创建一个新对象，合并作业分配和作业详情
            const formattedData = { 
              ...allocationRes.data,
              // 从作业详情获取关键信息
              title: assignmentRes.data.title,
              description: assignmentRes.data.description,
              deadline: assignmentRes.data.deadline,
              // 最关键的：从作业实体获取资源URL
              attachmentUrl: assignmentRes.data.resourceUrl
            }
            
            // 如果有提交记录，合并评语和分数以及提交信息
            if (submissionRes && submissionRes.code === 200 && submissionRes.data) {
              console.log('获取提交记录成功:', submissionRes.data);
              // 评语和分数
              formattedData.feedback = submissionRes.data.feedback;
              if (!formattedData.score && submissionRes.data.score) {
                formattedData.score = submissionRes.data.score;
              }
              
              // 提交记录信息
              formattedData.submissionUrl = submissionRes.data.fileUrl;
              formattedData.submissionTime = submissionRes.data.submitTime;
              formattedData.submissionId = submissionRes.data.submissionId;
              
              // 打印提交文件URL和提交时间用于调试
              console.log('提交文件URL:', formattedData.submissionUrl);
              console.log('提交时间:', formattedData.submissionTime);
            } else if ((isGraded || isSubmitted) && (!submissionRes || submissionRes.code !== 200)) {
              console.warn('获取提交记录失败或为空，但作业状态显示已提交/已批改');
              // 状态不匹配，可能需要更新状态
              if (isSubmitted) {
                formattedData.status = 'pending';
                console.log('由于找不到提交记录，将状态从submitted更新为pending');
              }
            }
            
            // 将数字状态码转换为文本状态
            if (typeof formattedData.status === 'number') {
              const statusMap = {
                0: 'pending',
                1: 'submitted',
                2: 'graded',
                3: 'overdue'
              }
              formattedData.status = statusMap[formattedData.status] || 'pending'
              console.log('提交页状态转换:', formattedData.status)
            }
            
            Object.assign(this.currentHomework, formattedData)
            
            // 添加调试信息，查看评语数据
            console.log('合并后的作业数据:', this.currentHomework)
            console.log('评语内容:', this.currentHomework.feedback)
            console.log('评语字段类型:', typeof this.currentHomework.feedback)
            
            // 保存分配ID，用于提交作业
            this.allocationId = allocationRes.data.allocationId
            
            // 如果没有获取到分配ID，给出提示
            if (!this.allocationId) {
              console.warn('未获取到作业分配ID')
              this.$message.warning('未获取到作业分配ID，可能影响提交')
            }
            
            // 获取提交历史记录
            this.loadingHistory = true;
            // 获取该作业的所有提交记录
            getSubmissionsByAssignmentId(homework.id)
              .then(historyRes => {
                if (historyRes.code === 200 && historyRes.data) {
                  // 筛选当前学生的提交记录
                  const mySubmissions = historyRes.data.filter(s => s.studentId === this.studentId);
                  console.log('所有提交记录:', historyRes.data);
                  console.log('我的提交记录:', mySubmissions);
                  
                  if (mySubmissions.length > 0) {
                    // 排序：按版本号或提交时间降序
                    mySubmissions.sort((a, b) => {
                      // 优先按版本号排序
                      if (a.version && b.version) {
                        return b.version - a.version;
                      }
                      // 其次按提交时间排序
                      const timeA = new Date(a.submitTime || a.createTime).getTime();
                      const timeB = new Date(b.submitTime || b.createTime).getTime();
                      return timeB - timeA;
                    });
                    
                    // 标记最新版本
                    mySubmissions[0].isLatest = true;
                    
                    // 处理提交历史数据
                    this.submissionHistory = mySubmissions.map(submission => {
                      return {
                        submissionId: submission.submissionId,
                        version: submission.version || '未知',
                        submitTime: this.formatDate(submission.submitTime || submission.createTime),
                        rawSubmitTime: submission.submitTime || submission.createTime,
                        fileUrl: submission.fileUrl,
                        status: submission.status,
                        isLatest: !!submission.isLatest
                      };
                    });
                    
                    console.log('处理后的提交历史:', this.submissionHistory);
                  } else {
                    console.log('未找到该学生关于此作业的提交记录');
                    this.submissionHistory = [];
                  }
                } else {
                  console.warn('获取提交历史记录失败');
                  this.submissionHistory = [];
                }
                this.loadingHistory = false;
              })
              .catch(err => {
                console.error('获取提交历史记录出错:', err);
                this.submissionHistory = [];
                this.loadingHistory = false;
              });
            
            // 检查作业是否已经提交过但未批改
            const isResubmit = this.currentHomework.status === 'submitted';
            
            // 重置表单
      this.homeworkForm = {
              file: null
      }
      this.fileList = []
            
            // 打开对话框
      this.homeworkDialogVisible = true
            
            // 如果是重新提交，添加提示
            if (isResubmit) {
              this.$message({
                message: '您正在重新提交作业，提交后将覆盖之前的提交内容',
                type: 'warning',
                duration: 3000
              });
            }
          } else {
            if (allocationRes.code !== 200) {
              this.$message.error(allocationRes.message || '获取作业分配失败')
            }
            if (assignmentRes.code !== 200) {
              this.$message.error(assignmentRes.message || '获取作业详情失败')
            }
            if (submissionRes && submissionRes.code !== 200) {
              this.$message.error(submissionRes.message || '获取提交记录失败')
            }
          }
        })
        .catch(err => {
          console.error('获取作业详情出错:', err)
          // 检查是否是作业分配不存在的错误
          if (err.message && err.message.includes('作业分配记录不存在')) {
            console.log('作业分配记录不存在，尝试创建分配记录...')
            // 创建作业分配记录
            createAssignmentAllocation(homework.id, this.studentId)
              .then(createRes => {
                if (createRes.code === 200) {
                  console.log('创建作业分配记录成功，重新获取作业详情')
                  // 重新尝试获取作业详情
                  this.handleHomework(homework)
                } else {
                  this.$message.error(createRes.message || '创建作业分配记录失败')
                  this.loadingDetail = false
                }
              })
              .catch(createErr => {
                console.error('创建作业分配记录出错:', createErr)
                this.$message.error('创建作业分配记录失败，请稍后重试')
                this.loadingDetail = false
              })
          } else {
          this.$message.error('获取作业详情失败，请稍后重试')
            this.loadingDetail = false
          }
        })
        .finally(() => {
          // 已经在catch中设置了loadingDetail = false，这里不需要重复设置
        })
    },
    
    // 处理文件变更
    handleFileChange(file, fileList) {
      if (this.validateFile(file)) {
        this.fileList = fileList.slice(-1)  // 只保留最后一个文件
        this.homeworkForm.file = file.raw
      } else {
        this.fileList = []
      }
    },
    
    // 验证文件
    validateFile(file) {
      // 检查文件大小
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('上传文件大小不能超过 20MB')
        return false
      }
      
      // 检查文件类型（可选）
      const allowedTypes = [
        'application/msword', 
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/pdf',
        'application/zip',
        'application/x-rar-compressed',
        'application/x-7z-compressed',
        'application/x-tar',
        'text/plain',
        'image/jpeg',
        'image/png',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      ]
      
      // 使用更宽松的验证，允许任何文件类型，但提示用户
      if (!allowedTypes.includes(file.raw.type)) {
        this.$confirm('该文件类型可能不被支持，是否继续上传?', '警告', {
          confirmButtonText: '继续上传',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return true
        }).catch(() => {
          this.fileList = []
          this.homeworkForm.file = null
          return false
        })
      }
      
      return true
    },
    
    // 处理文件移除
    handleFileRemove() {
      this.fileList = []
      this.homeworkForm.file = null
      return true
    },
    
    // 下载附件
    downloadAttachment(url) {
      if (!url) {
        this.$message.warning('附件链接不存在')
        return
      }
      
      // 获取原始文件名
      const originalFileName = this.getOriginalFileName(url)
      
      // 直接使用a标签的download属性实现下载
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', originalFileName)
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('文件下载已开始')
    },
    
    // 获取原始文件名（从URL中提取）
    getOriginalFileName(url) {
      if (!url) return '';
      
      // 记录原始URL以便调试
      console.log('提取文件名的原始URL:', url);
      
      try {
        // 格式1: 从name参数中获取Base64编码的原始文件名（阿里云OSS服务实现）
        const urlObj = new URL(url);
        const encodedName = urlObj.searchParams.get('name');
        
        if (encodedName) {
          // 解码BASE64编码的原始文件名
          try {
            // 使用window.atob解码BASE64字符串
            const base64Decoded = atob(encodedName);
            
            // 将UTF-8编码的字节转换为JavaScript字符串
            // 这种方法可以正确处理中文等非ASCII字符
            const bytes = new Uint8Array(base64Decoded.length);
            for (let i = 0; i < base64Decoded.length; i++) {
              bytes[i] = base64Decoded.charCodeAt(i);
            }
            const decodedName = new TextDecoder('utf-8').decode(bytes);
            
            console.log('从URL查询参数中解码的原始文件名:', decodedName);
            return decodedName;
          } catch (e) {
            console.error('BASE64解码失败:', e);
          }
        }
        
        // 格式2: 从其他可能的查询参数中获取原始文件名
        let match = url.match(/[?&]original=([^&]+)/);
        if (!match) {
          match = url.match(/[?&]filename=([^&]+)/);
        }
        
        if (match && match[1]) {
          const decodedName = decodeURIComponent(match[1]);
          console.log('从查询参数中提取的文件名:', decodedName);
          return decodedName;
        }
        
        // 格式3: 尝试通过path中的文件名获取，阿里云OSS常用格式
        // 例如: https://bucket.oss-region.aliyuncs.com/path/originalname_timestamp.ext
        // 或者: https://bucket.oss-region.aliyuncs.com/path/timestamp_originalname.ext
        const pathSegments = url.split('/');
        const lastSegment = pathSegments[pathSegments.length - 1];
        
        // 去掉查询参数部分
        const filename = lastSegment.split('?')[0];
        
        // 尝试从文件名中提取原始名称
        // 格式: 原始名_时间戳.扩展名 或 时间戳_原始名.扩展名
        const filenameMatch = filename.match(/(.+)_\d+\.(\w+)$/) || filename.match(/\d+_(.+)\.(\w+)$/);
        if (filenameMatch) {
          const extractedName = filenameMatch[1] + '.' + filenameMatch[2];
          console.log('从路径中提取的原始文件名:', extractedName);
          return extractedName;
        }
        
        // 格式4: 如果是UUID格式，尝试从文件扩展名推断一个有意义的名称
        if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.\w+$/i.test(filename) ||
            /^[0-9a-f]{32}\.\w+$/i.test(filename)) {
          // 是UUID格式，获取扩展名
          const ext = filename.split('.').pop();
          const typeNames = {
            'pdf': '作业说明书.pdf',
            'doc': '作业文档.doc',
            'docx': '作业文档.docx',
            'xls': '作业表格.xls',
            'xlsx': '作业表格.xlsx',
            'ppt': '作业演示文稿.ppt',
            'pptx': '作业演示文稿.pptx',
            'txt': '作业文本.txt',
            'zip': '作业资料包.zip',
            'rar': '作业资料包.rar',
            'jpg': '作业图片.jpg',
            'jpeg': '作业图片.jpeg',
            'png': '作业图片.png'
          };
          const friendlyName = typeNames[ext.toLowerCase()] || `作业文件.${ext}`;
          console.log('根据扩展名生成的友好文件名:', friendlyName);
          return friendlyName;
        }
        
        // 最后回退到使用完整文件名
        console.log('使用默认文件名:', filename);
        return filename;
      } catch (error) {
        console.error('解析文件名出错:', error);
        return '未知文件';
      }
    },
    
    // 直接下载文件（不使用API调用）
    directDownload(url) {
      if (!url) {
        this.$message.warning('文件链接不存在')
        return
      }
      
      // 获取原始文件名
      const originalFileName = this.getOriginalFileName(url)
      console.log('下载使用的文件名:', originalFileName)
      
      // 直接使用a标签的download属性实现下载
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', originalFileName)
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('文件下载已开始')
    },
    
    // 提交作业
    submitHomework() {
      // 如果是只读模式（已批改作业），不允许提交
      if (this.isViewOnly) {
        this.$message.warning('已批改的作业不能再次提交')
        return
      }
      
      this.$refs.homeworkForm.validate(valid => {
        if (valid) {
          if (!this.currentHomework.assignmentId) {
            this.$message.error('作业ID不存在，无法提交')
            return
          }
          
          if (!this.homeworkForm.file) {
            this.$message.warning('请选择要提交的文件')
            return
          }
          
          // 提交前确认
          this.$confirm(`确定要提交作业吗？${this.isOverdue(this.currentHomework.deadline) ? '注意：该作业已超期，提交后将会被标记为超期提交' : ''}`, '提交确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: this.isOverdue(this.currentHomework.deadline) ? 'warning' : 'info'
          }).then(() => {
            // 设置提交中状态
            this.submitting = true
            this.showUploadProgress = true
            this.uploadProgress = 0
            
            // 模拟上传进度
            const progressInterval = setInterval(() => {
              if (this.uploadProgress < 90) {
                this.uploadProgress += Math.floor(Math.random() * 10) + 1
              }
            }, 300)
            
            // 创建提交数据对象
            const submissionData = {
              assignmentId: this.currentHomework.assignmentId,
              studentId: this.studentId
            }
            
            // 检查是否为超期提交
            if (this.isOverdue(this.currentHomework.deadline) || this.currentHomework.originalStatus === 'overdue') {
              submissionData.isOverdue = true; // 添加超期标记
              console.log('超期提交作业，添加超期标记');
            }
            
            console.log('准备提交作业数据:', submissionData)
            console.log('文件信息:', this.homeworkForm.file.name, this.homeworkForm.file.size)
            
            // 直接提交作业和文件
            submitAssignment(submissionData, this.homeworkForm.file)
              .then(res => {
                // 更新进度为100%，表示完成
                this.uploadProgress = 100
                clearInterval(progressInterval)
                
                if (res.code === 200) {
                  console.log('作业提交成功:', res.data)
                  
                  // 立即更新当前作业的状态为已提交
                  const index = this.assignments.findIndex(a => 
                    a.id === this.currentHomework.assignmentId || 
                    a.assignmentId === this.currentHomework.assignmentId
                  );
                  
                  if (index !== -1) {
                    console.log(`更新本地作业状态: 作业ID=${this.currentHomework.assignmentId}, 索引=${index}, 旧状态=${this.assignments[index].status}`);
                    this.assignments[index].status = 'submitted';
                    console.log(`状态已更新为: ${this.assignments[index].status}`);
                  } else {
                    console.warn(`未找到要更新的作业: ID=${this.currentHomework.assignmentId}`);
                    console.log('当前作业列表:', this.assignments.map(a => ({id: a.id, assignmentId: a.assignmentId, title: a.title})));
                  }
                  
                  // 更新当前作业信息，立即显示提交文件
                  if (res.data) {
                    // 如果后端返回了提交记录，直接使用
                    if (res.data.fileUrl) {
                      this.currentHomework.submissionUrl = res.data.fileUrl;
                      console.log('设置提交文件URL:', this.currentHomework.submissionUrl);
                    }
                    
                    // 设置提交时间为当前时间
                    this.currentHomework.submissionTime = res.data.submitTime || new Date().toISOString();
                    this.currentHomework.status = 'submitted';
                    
                    // 如果有提交ID，保存它
                    if (res.data.submissionId) {
                      this.currentHomework.submissionId = res.data.submissionId;
                    }
                  } else {
                    // 后端没有返回提交记录数据，使用本地上传的文件名作为临时显示
                    console.log('后端未返回提交记录数据，使用本地文件名作为临时显示');
                    this.currentHomework.submissionTime = new Date().toISOString();
                    this.currentHomework.status = 'submitted';
                    
                    // 提交成功后，我们需要重新获取提交记录以显示正确的提交文件URL
                    const { getSubmissionByAssignmentIdAndStudentId } = require('@/api/submission');
                    getSubmissionByAssignmentIdAndStudentId(this.currentHomework.assignmentId, this.studentId)
                      .then(submissionRes => {
                        if (submissionRes.code === 200 && submissionRes.data) {
                          console.log('提交后获取提交记录成功:', submissionRes.data);
                          this.currentHomework.submissionUrl = submissionRes.data.fileUrl;
                          this.currentHomework.submissionTime = submissionRes.data.submitTime;
                          this.currentHomework.submissionId = submissionRes.data.submissionId;
                          
                          // 获取最新的提交历史记录
                          this.refreshSubmissionHistory(this.currentHomework.assignmentId);
                        }
                      })
                      .catch(err => {
                        console.error('提交后获取提交记录失败:', err);
                      });
                  }
                  
                  // 延迟关闭对话框，让用户看到100%进度
                  setTimeout(() => {
          this.$message.success('作业提交成功')
          this.homeworkDialogVisible = false
                    
                    // 重置表单
                    this.homeworkForm = {
                      file: null
                    }
                    this.fileList = []
                    this.showUploadProgress = false
                    
                    // 刷新列表，但本地状态已经更新
                    this.fetchAssignments()
                  }, 800)
                } else {
                  console.error('作业提交失败:', res.message)
                  this.$message.error(res.message || '作业提交失败')
                  this.showUploadProgress = false
                }
              })
              .catch(err => {
                clearInterval(progressInterval)
                this.showUploadProgress = false
                console.error('提交作业出错:', err)
                this.$message.error(err.message || '作业提交失败，请稍后重试')
              })
              .finally(() => {
                this.submitting = false
              })
          }).catch(() => {
            // 用户取消提交
          })
        } else {
          this.$message.warning('请完成必填项')
        }
      })
    },
    
    // 获取状态类型
    getStatusType(status) {
      // 处理数字状态
      if (typeof status === 'number') {
        const statusMap = {
          0: 'warning', // pending
          1: 'success', // submitted
          2: 'info',    // graded
          3: 'danger'   // overdue
        };
        return statusMap[status] || 'info';
      }
      
      // 处理字符串格式的数字（如 "1"）
      if (typeof status === 'string' && /^[0-3]$/.test(status)) {
        const numStatus = parseInt(status, 10);
        const statusMap = {
          0: 'warning', // pending
          1: 'success', // submitted
          2: 'info',    // graded
          3: 'danger'   // overdue
        };
        return statusMap[numStatus] || 'info';
      }
      
      // 处理字符串状态
      const types = {
        pending: 'warning',
        submitted: 'success',
        graded: 'info',
        overdue: 'danger'
      };
      return types[status] || 'info';
    },
    
    // 获取状态文本
    getStatusText(status) {
      // 处理数字状态码
      if (typeof status === 'number') {
        const statusMap = {
          0: '待提交',
          1: '已提交',
          2: '已批改',
          3: '已超期'
        };
        return statusMap[status] || '未知状态';
      }
      
      // 处理字符串状态
      const texts = {
        pending: '待提交',
        submitted: '已提交',
        graded: '已批改',
        overdue: '已超期'
      };
      return texts[status] || status;
    },
    

    
    // 判断是否即将截止
    isCloseToDeadline(deadline) {
      if (!deadline) return false
      const now = new Date()
      const deadlineDate = new Date(deadline)
      const timeDiff = deadlineDate.getTime() - now.getTime()
      const hoursDiff = Math.floor(timeDiff / (1000 * 3600))
      return hoursDiff <= 24
    },
    
    // 处理表单提交
    cancelSubmit() {
      this.$confirm('确定要取消提交吗？已填写的内容将不会保存', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '返回编辑',
        type: 'warning'
      }).then(() => {
        this.homeworkDialogVisible = false
        this.homeworkForm = {
          file: null
        }
        this.fileList = []
        this.uploadProgress = 0
        this.showUploadProgress = false
      }).catch(() => {
        // 用户选择继续编辑，不做任何处理
      })
    },
    
    // 处理表单上传前
    beforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.warning('上传文件大小不能超过 20MB')
      }
      return isLt20M
    },
    
    // 处理表单超出限制
    handleExceed() {
      this.$message.warning('只能上传一个文件，且大小不超过 20MB')
      return false
    },
    
    // 显示原始数据，用于调试
    showRawData() {
      console.log('原始作业详情数据:', JSON.stringify(this.currentHomework, null, 2))
      this.$alert(
        `<pre>${JSON.stringify(this.currentHomework, null, 2)}</pre>`, 
        '调试信息 - 原始数据', 
        {
          dangerouslyUseHTMLString: true,
          customClass: 'debug-dialog'
        }
      )
    },
    
    // 格式化文件大小
    formatFileSize(size) {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + ' MB'
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
      }
    },
    
    // 刷新提交历史记录
    refreshSubmissionHistory(assignmentId) {
      if (!assignmentId || !this.studentId) return;
      
      console.log('刷新提交历史记录，作业ID:', assignmentId);
      this.loadingHistory = true;
      
      getSubmissionsByAssignmentId(assignmentId)
        .then(historyRes => {
          if (historyRes.code === 200 && historyRes.data) {
            // 筛选当前学生的提交记录
            const mySubmissions = historyRes.data.filter(s => s.studentId === this.studentId);
            console.log('刷新获取到的所有提交记录:', historyRes.data);
            console.log('刷新获取到的我的提交记录:', mySubmissions);
            
            if (mySubmissions.length > 0) {
              // 排序：按版本号或提交时间降序
              mySubmissions.sort((a, b) => {
                // 优先按版本号排序
                if (a.version && b.version) {
                  return b.version - a.version;
                }
                // 其次按提交时间排序
                const timeA = new Date(a.submitTime || a.createTime).getTime();
                const timeB = new Date(b.submitTime || b.createTime).getTime();
                return timeB - timeA;
              });
              
              // 标记最新版本
              mySubmissions[0].isLatest = true;
              
              // 处理提交历史数据
              this.submissionHistory = mySubmissions.map(submission => {
                return {
                  submissionId: submission.submissionId,
                  version: submission.version || '未知',
                  submitTime: this.formatDate(submission.submitTime || submission.createTime),
                  rawSubmitTime: submission.submitTime || submission.createTime,
                  fileUrl: submission.fileUrl,
                  status: submission.status,
                  isLatest: !!submission.isLatest
                };
              });
              
              console.log('刷新后的提交历史:', this.submissionHistory);
            } else {
              console.log('刷新未找到该学生关于此作业的提交记录');
              this.submissionHistory = [];
            }
          } else {
            console.warn('刷新提交历史记录失败');
            this.submissionHistory = [];
          }
          this.loadingHistory = false;
        })
        .catch(err => {
          console.error('刷新提交历史记录出错:', err);
          this.submissionHistory = [];
          this.loadingHistory = false;
        });
    },
    
    // 添加返回首页方法
    goToHomepage() {
      this.$router.push('/student/dashboard');
    },
    
    // 获取测试状态类型
    getQuizStatusType(status) {
      const statusNum = Number(status);
      switch (statusNum) {
        case 0: return 'info';    // 未开始
        case 1: return 'success'; // 进行中
        case 2: return 'warning'; // 已结束
        default: return 'info';
      }
    },
    
    // 获取测试状态文本
    getQuizStatusText(status) {
      const statusNum = Number(status);
      switch (statusNum) {
        case 0: return '未开始';
        case 1: return '进行中';
        case 2: return '已结束';
        default: return '未知';
      }
    },
    
    // 处理随堂测试
    handleQuiz(quiz) {
      const status = Number(quiz.status);
      
      // 如果测试未开始，提示用户
      if (status === 0) {
        this.$message.warning('该测试尚未开始，请等待教师开启测试后再进行答题');
        return;
      } 
      // 只有进行中的测试才能答题
      else if (status === 1) {
        // 检查是否已提交过
        isSubmitted(quiz.quizId, this.studentId)
          .then(response => {
            if (response.code === 200) {
              const submitted = response.data || false;
              if (submitted) {
                // 已提交过，查看结果
                this.viewQuizResult(quiz);
                this.$message.info('您已提交过此测试，查看结果');
              } else {
                // 未提交过，开始答题
                this.openQuizDialog(quiz);
              }
            } else {
              // 接口错误，默认允许答题
              this.openQuizDialog(quiz);
            }
          })
          .catch(error => {
            console.error('检查提交状态出错:', error);
            // 错误情况下允许答题
            this.openQuizDialog(quiz);
          });
      } else {
        // 已结束的测试，查看详情
        this.viewQuizResult(quiz);
      }
    },
    
    // 打开答题对话框
    openQuizDialog(quiz) {
      this.quizDialogVisible = true;
      this.currentQuiz = quiz;
      this.quizLoading = true;
      this.quizForm = {
        answers: []
      };
      
      // 获取题目
      getQuizQuestions(quiz.quizId)
        .then(response => {
          if (response.code === 200) {
            this.quizQuestions = response.data || [];
            
            // 初始化答案数组
            this.quizForm.answers = this.quizQuestions.map(q => ({
              questionId: q.questionId,
              answer: ''
            }));
            
            console.log('获取题目成功:', this.quizQuestions);
          } else {
            this.$message.error(response.message || '获取题目失败');
          }
        })
        .catch(error => {
          console.error('获取题目出错:', error);
          this.$message.error('获取题目失败，请稍后重试');
        })
        .finally(() => {
          this.quizLoading = false;
        });
    },
    
    // 查看测试结果
    viewQuizResult(quiz) {
      this.resultDialogVisible = true;
      this.currentQuiz = quiz;
      this.quizLoading = true;
      
      // 先获取题目
      Promise.all([
        getQuizQuestions(quiz.quizId),
        getStudentSubmission(quiz.quizId, this.studentId).catch(error => {
          // 捕获"未找到提交记录"的错误，返回一个假的响应，避免报错
          console.log('未找到提交记录，创建默认0分记录:', error.message);
          return { code: 200, data: { score: 0, answers: '{}', correctCount: 0 } };
        })
      ])
        .then(([questionsRes, submissionRes]) => {
          if (questionsRes.code === 200) {
            this.quizQuestions = questionsRes.data || [];
          } else {
            this.$message.error(questionsRes.message || '获取题目失败');
          }
          
          if (submissionRes.code === 200) {
            this.quizSubmission = submissionRes.data;
            console.log('获取提交记录成功:', this.quizSubmission);
            
            // 不管后端是否返回了分数，都重新计算正确题数和正确率
            if (this.quizSubmission && this.quizQuestions.length > 0) {
              // 重新计算正确题数
              try {
                const userAnswers = JSON.parse(this.quizSubmission.answers || '{}');
                let correctCount = 0;
                
                // 计算正确题数
                this.quizQuestions.forEach(question => {
                  // 直接从对象中获取答案
                  const userAnswer = userAnswers[question.questionId];
                  if (userAnswer !== undefined && String(userAnswer) === String(question.correctAnswer)) {
                    correctCount++;
                  }
                });
                
                // 更新提交对象中的正确题数字段
                this.quizSubmission.correctCount = correctCount;
                console.log(`手动计算正确题数: ${correctCount}/${this.quizQuestions.length}`);
              } catch (error) {
                console.error('计算正确题数出错:', error);
              }
            }
          } else {
            // 创建一个默认的提交对象，得分为0
            this.quizSubmission = { score: 0, answers: '{}', correctCount: 0 };
            console.log('创建默认提交记录:0分');
          }
        })
        .catch(error => {
          console.error('获取测试结果出错:', error);
          // 不向用户显示错误，而是创建一个默认的0分提交记录
          this.quizSubmission = { score: 0, answers: '{}', correctCount: 0 };
          console.log('发生错误，创建默认提交记录:0分');
        })
        .finally(() => {
          this.quizLoading = false;
        });
    },
    
    // 前端计算分数和正确题数(当后端未计算时使用)
    calculateScore() {
      if (!this.quizSubmission || !this.quizQuestions.length) return;
      
      try {
        // 改为键值对格式解析
        const userAnswers = JSON.parse(this.quizSubmission.answers || '{}');
        let correctCount = 0;
        
        // 计算正确题数
        this.quizQuestions.forEach(question => {
          // 直接从对象中获取答案
          const userAnswer = userAnswers[question.questionId];
          if (userAnswer !== undefined && String(userAnswer) === String(question.correctAnswer)) {
            correctCount++;
          }
        });
        
        // 每题10分
        const score = correctCount * 10;
        
        console.log(`前端计算分数: ${score}, 正确题数: ${correctCount}/${this.quizQuestions.length}`);
        
        // 更新提交对象，仅用于前端显示
        this.quizSubmission.score = score;
        this.quizSubmission.correctCount = correctCount;
      } catch (error) {
        console.error('计算分数出错:', error);
      }
    },
    
    // 选择答案
    selectAnswer(questionIndex, optionIndex) {
      if (this.quizForm.answers[questionIndex]) {
        this.quizForm.answers[questionIndex].answer = String(optionIndex);
      }
    },
    
    // 获取选项样式
    getOptionClass(question, optIndex) {
      if (!this.resultDialogVisible) return '';
      
      // 在结果页面中
      if (!this.quizSubmission || !this.quizSubmission.answers) return '';
      
      try {
        // 修改为键值对格式的解析方式
        const userAnswers = JSON.parse(this.quizSubmission.answers || '{}');
        // 直接从对象中获取答案，使用问题ID作为键
        const userAnswer = userAnswers[question.questionId];
        
        // 将所有比较值转换为字符串，确保类型一致
        const indexStr = String(optIndex);
        const correctAnswerStr = String(question.correctAnswer);
        
        // 如果是正确答案
        if (indexStr === correctAnswerStr) {
          return 'correct-option';
        }
        
        // 如果是用户选择的答案且不是正确答案
        if (userAnswer !== undefined && String(userAnswer) === indexStr && indexStr !== correctAnswerStr) {
          return 'wrong-option';
        }
        
        // 如果是用户选择的答案且是正确答案
        if (userAnswer !== undefined && String(userAnswer) === indexStr && indexStr === correctAnswerStr) {
          return 'correct-option';
        }
        
        return '';
      } catch (error) {
        console.error('解析答案数据出错:', error);
        return '';
      }
    },
    
    // 检查是否已选择所有题目
    checkAllAnswered() {
      return this.quizForm.answers.every(a => a.answer !== '');
    },
    
    // 处理提交按钮点击
    submitQuizAnswers() {
      // 检查是否已选择所有题目的答案
      if (!this.checkAllAnswered()) {
        this.$confirm('您还有题目未作答，确定要提交吗？', '提交确认', {
          confirmButtonText: '确定提交',
          cancelButtonText: '返回继续作答',
          type: 'warning'
        }).then(() => {
          this.doSubmitQuiz();
        }).catch(() => {
          // 用户取消提交，返回继续作答
        });
      } else {
        this.doSubmitQuiz();
      }
    },

    // 执行提交操作
    doSubmitQuiz() {
      this.quizSubmitting = true;
      
      // 检查是否有未回答的题目
      const unansweredQuestions = this.quizForm.answers.filter(a => a.answer === '');
      if (unansweredQuestions.length > 0) {
        this.$confirm(`有${unansweredQuestions.length}道题目未作答，确定要提交吗？`, '提交确认', {
          confirmButtonText: '确定提交',
          cancelButtonText: '返回修改',
          type: 'warning'
        }).then(() => {
          this.submitQuizToServer();
        }).catch(() => {
          this.quizSubmitting = false;
        });
      } else {
        this.submitQuizToServer();
      }
    },
    
    // 将答案提交到服务器
    submitQuizToServer() {
      // 确保所有答案格式一致
      const formattedAnswers = this.quizForm.answers.map(answer => ({
        questionId: answer.questionId,
        answer: answer.answer === '' ? null : String(answer.answer) // 使用null表示未作答
      }));
      
      // 计算分数和正确题数
      let correctCount = 0;
      this.quizQuestions.forEach(question => {
        const answer = formattedAnswers.find(a => a.questionId === question.questionId);
        if (answer && answer.answer !== null && String(answer.answer) === String(question.correctAnswer)) {
          correctCount++;
        }
      });
      
      // 每题10分
      const score = correctCount * 10;
      
      console.log(`前端计算分数: ${score}, 正确题数: ${correctCount}/${this.quizQuestions.length}`);
      
      // 创建简化的键值对格式，这是后端能正确处理的格式
      const simpleAnswers = {};
      formattedAnswers.forEach(a => {
        simpleAnswers[a.questionId] = a.answer;
      });
      
      // 构建提交数据，将分数信息包含其中
      const submitData = {
        quizId: this.currentQuiz.quizId,
        studentId: this.studentId,
        answers: JSON.stringify(simpleAnswers),
        score: score,
        correctCount: correctCount,
        totalCount: this.quizQuestions.length
      };
      
      console.log('提交数据:', submitData);
      
      // 使用简化后的键值对格式提交
      this.quizSubmitting = true;
      submitQuiz(submitData)
        .then(response => {
          if (response.code === 200) {
            this.handleSubmitSuccess(response);
          } else {
            this.$message.error(response.message || '提交失败，请联系管理员');
          }
        })
        .catch(error => {
          console.error('提交测试答案出错:', error);
          this.$message.error('提交测试答案失败，请稍后重试');
        })
        .finally(() => {
          this.quizSubmitting = false;
        });
    },
    
    // 处理提交成功的响应
    handleSubmitSuccess(response) {
      console.log('提交成功，服务器响应:', response);
      this.$message.success('提交成功');
      this.quizDialogVisible = false;
      
      // 更新测试状态
      this.fetchQuizzes();
      
      // 延迟查看结果，确保后端有时间处理
      setTimeout(() => {
        this.viewQuizResult(this.currentQuiz);
      }, 1000);
    },
    getUserAnswer(question) {
      if (!this.quizSubmission || !this.quizSubmission.answers) return null;
      try {
        // 改为键值对格式解析
        const userAnswers = JSON.parse(this.quizSubmission.answers || '{}');
        // 直接从对象中获取答案
        return userAnswers[question.questionId];
      } catch (error) {
        console.error('解析用户答案出错:', error);
        return null;
      }
    }
  }
}
</script>

<style scoped>
.course-detail-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.course-header {
  position: relative;
  background: transparent;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  min-height: 180px;
  overflow: hidden;
}

/* 背景层样式 */
.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('@/assets/2.jpg') center/cover;
  filter: brightness(0.9);
  z-index: 1;
}

/* 文字样式 */
.course-info {
  position: relative;
  z-index: 2;
  padding: 15px 0;
}

.course-info h2 {
  margin: 0 0 10px;
  color: white;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
  font-size: 28px;
}

.course-info p {
  margin: 0 0 5px;
  color: rgba(255,255,255,0.9);
  font-size: 16px;
}

.course-stats {
  display: flex;
  gap: 20px;
  position: relative;
  z-index: 2;
  color: white;
  margin-top: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  color: rgba(255,255,255,0.9);
}

.stat-item i {
  margin-right: 5px;
  font-size: 20px;
}

.nav-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  overflow: hidden;
}

.content-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  min-height: 400px;
}

.homework-content {
  margin-bottom: 20px;
}

.announcement-content {
  margin-bottom: 20px;
}

.resource-section {
  margin-top: 20px;
}

.notice-item {
  padding: 15px 0;
  border-bottom: 1px solid #EBEEF5;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.notice-header h4 {
  margin: 0;
  color: #303133;
  font-weight: bold;
}

.notice-time {
  color: #909399;
  font-size: 13px;
}

.notice-content {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  white-space: pre-line;
}

.homework-description,
.description {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  line-height: 1.6;
  margin-bottom: 15px;
  white-space: pre-line;
  color: #303133;
}

.attachment-list {
  margin-top: 10px;
}

.attachment-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 6px;
  border: 1px solid #EBEEF5;
}

.attachment-item i {
  margin-right: 10px;
  color: #409EFF;
  font-size: 20px;
}

.attachment-item span {
  flex: 1;
  color: #303133;
  font-size: 14px;
}

.homework-detail {
  padding: 20px 0;
}

.detail-header {
  margin-bottom: 20px;
  text-align: center;
}

.detail-header h3 {
  margin: 0 0 10px 0;
  font-size: 22px;
  color: #303133;
  font-weight: bold;
}

.detail-deadline {
  color: #606266;
  font-size: 14px;
}

.divider {
  height: 1px;
  background-color: #EBEEF5;
  margin: 20px 0;
}

.attachment-section {
  padding: 0 20px;
}

.attachment-section h4 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 15px;
}

.empty-attachment {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px;
  background-color: #f8f8f8;
  border-radius: 6px;
  border: 1px dashed #EBEEF5;
  color: #909399;
}

.empty-attachment i {
  font-size: 20px;
  margin-right: 10px;
  color: #E6A23C;
}

.dialog-footer {
  text-align: center;
  margin-top: 10px;
}

.form-title {
  text-align: center;
  margin-bottom: 20px;
}

.attachment-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 6px;
  border: 1px solid #EBEEF5;
}

.attachment-item i {
  margin-right: 10px;
  color: #409EFF;
  font-size: 20px;
}

.attachment-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.attachment-name {
  color: #303133;
  font-size: 14px;
  margin-bottom: 4px;
}

.attachment-url {
  color: #909399;
  font-size: 12px;
  word-break: break-all;
}

.description-section {
  padding: 0 20px;
}

.description-section h4 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 15px;
}

.submission-section {
  padding: 0 20px;
  margin-top: 20px;
}

.submission-section h4 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 15px;
}

.comment-section {
  margin-top: 15px;
}

.comment-section h5 {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.comment-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  line-height: 1.5;
}

.grade-section {
  margin-top: 20px;
}

.grade-section h5 {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.grade-info {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.grade-score {
  margin-bottom: 8px;
}

.score {
  font-weight: bold;
  color: #F56C6C;
}

.grade-feedback {
  color: #606266;
  line-height: 1.5;
}

/* 提交历史记录样式 */
.submission-history-section {
  margin-top: 15px;
}

.submission-history-section h5 {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

/* 调试对话框样式 */
::v-deep .debug-dialog {
  width: 80%;
  max-width: 800px;
}

::v-deep .debug-dialog .el-message-box__content {
  max-height: 500px;
  overflow: auto;
}

::v-deep .debug-dialog pre {
  white-space: pre-wrap;
  word-break: break-word;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 5px;
  font-family: monospace;
  font-size: 12px;
  line-height: 1.5;
}

/* 添加文件链接样式 */
.file-link {
  flex: 1;
  color: #409EFF;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color 0.3s;
}

.file-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.attachment-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 6px;
  border: 1px solid #EBEEF5;
}

.attachment-item i {
  margin-right: 10px;
  color: #409EFF;
  font-size: 20px;
}

.attachment-time {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.selected-file-info {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.selected-file-info i {
  margin-right: 5px;
}

.selected-file-info .file-name {
  color: #606266;
  font-size: 12px;
}

.selected-file-info .file-size {
  color: #909399;
  font-size: 10px;
}

.progress-text {
  text-align: center;
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}

.progress-text.success {
  color: #67C23A;
}

.upload-with-file .el-upload {
  display: none;
}

/* 返回按钮外层容器 */
.back-wrapper {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 10;
}

/* 修改返回按钮样式 */
.back-button {
  background-color: transparent;
  border: none;
  font-weight: 500;
  padding: 8px 15px;
  font-size: 14px;
  color: white;
  box-shadow: none;
}

.back-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.back-button:focus {
  background-color: transparent;
}

.quiz-content {
  margin-top: 10px;
}

/* 测验题目区域 */
.quiz-questions {
  margin-top: 20px;
}

.quiz-question {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.08);
}

.question-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 20px;
  line-height: 1.6;
  font-weight: 600;
}

.question-number {
  font-weight: bold;
  color: #409EFF;
  margin-right: 8px;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  display: flex;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #ebeef5;
}

.option-item:hover {
  background-color: #e9f5ff;
  border-color: #c6e2ff;
}

.option-selected {
  background-color: #e9f5ff;
  border-color: #409EFF;
  color: #409EFF;
}

.correct-option {
  background-color: #f0f9eb;
  border-color: #67c23a;
  color: #67c23a;
}

.wrong-option {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

.option-marker {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #fff;
  color: #606266;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 10px;
  border: 1px solid #dcdfe6;
}

.option-selected .option-marker {
  background-color: #409EFF;
  color: #fff;
  border-color: #409EFF;
}

.correct-option .option-marker {
  background-color: #67c23a;
  color: #fff;
  border-color: #67c23a;
}

.wrong-option .option-marker {
  background-color: #f56c6c;
  color: #fff;
  border-color: #f56c6c;
}

.option-text {
  flex: 1;
  line-height: 24px;
}

.no-questions {
  padding: 40px 0;
  text-align: center;
}

.question-explanation {
  margin-top: 15px;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-left: 3px solid #67c23a;
  border-radius: 4px;
}

.explanation-text {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

/* 测试结果页样式 */
.quiz-result {
  padding: 20px;
}

.quiz-score {
  text-align: center;
  margin-bottom: 30px;
}

.score-value {
  font-size: 42px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.score-text {
  color: #606266;
  font-size: 16px;
}

.quiz-stats {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin-bottom: 30px;
}

.stats-item {
  text-align: center;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stats-text {
  color: #606266;
  font-size: 14px;
}

.result-questions .quiz-question {
  box-shadow: none;
  border: 1px solid #ebeef5;
}

.no-submission {
  padding: 40px 0;
  text-align: center;
}

.quiz-description {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  padding: 0 20px;
  margin-bottom: 20px;
}

.explanation-text.user-answer {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.answer-correct {
  color: #67C23A;
}

.answer-wrong {
  color: #F56C6C;
}
</style> 